import json
from flask import render_template,request,session,Blueprint,redirect
from models.user import User
from models.house_info import house_info
from models.history import History
from utils.pageData import *
from utils.getPublicData import *
import random
import uuid
from app import app
import os
from pred import index
pb = Blueprint('page',__name__,url_prefix='/page',template_folder='templates')

@pb.route('/home',methods=['GET','POST'])
def home():
    username = session['username']
    cityDataList = getCityPriceChinaData()
    data1,data2 = getHomeRadarData()
    maxLen,maxPrice,maxhouseType,sale_statusMax,hisotryLen,maxPrices,sortCountCity = getHomeTagData(username)
    barData = getHisotryBarCharData(username)
    historyList = getHomeHisotryData()
    return render_template(
        "index.html",
        username=username,
        cityDataList=cityDataList,
        maxLen=maxLen,
        maxPrice=maxPrice,
        maxhouseType=maxhouseType,
        sale_statusMax=sale_statusMax,
        data1=data1,
        data2=data2,
        historyList=historyList,
        hisotryLen=hisotryLen,
        maxPrices=maxPrices,
        barData=barData,
        sortCountCity=sortCountCity
    )


@pb.route('/search',methods=['GET','POST'])
def search():
    username = session['username']
    houseList = getAllhouseInfoData()
    maxLen = len(houseList)
    if request.method == 'POST':
        houseListRandom = gethouseByhouseName(request.form['searchWord'])
        cityList = list(set([x.city for x in houseListRandom]))
    else:
        houseListRandom = [houseList[random.randint(1,maxLen)] for x in range(100)]   # 设置返回多少条数据
        cityList = list(set([x.city for x in houseListRandom]))
    return render_template(
        "search.html",
        username=username,
        houseList=houseListRandom,
        cityList=cityList
    )


# 数据管理页面
@pb.route('/tableData',methods=['GET','POST'])
def tableData():
    username = session['username']
    tableData = getTableDatahouse()[-100:]      # 若取全部数据，则页面会加载很久
    # tableData = getTableDatahouse()[-5:]    # 原来的
    return render_template(
        "tableData.html",
        username=username,
        tableData=tableData
    )

@pb.route('/detail',methods=['GET','POST'])
def detail():
    id = request.args.get('id')
    houseInfo = gethouseById(id)
    username = session['username']
    return render_template(
        "detail.html",
        username=username,
        houseInfo=houseInfo
    )

@pb.route('/deletehouse',methods=['GET','POST'])
def deletehouse():
    id = request.args.get('id')
    deletehouseInfo(id)
    return redirect('/page/tableData')

@pb.route('/edithouse',methods=['GET','POST'])
def edithouse():
    username = session['username']
    if request.method == 'GET':
        id = request.args.get('id')
        houseInfo = gethouseById(id)
        return render_template(
            "edithouse.html",
            username=username,
            houseInfo=houseInfo,
            id=id
        )
    else:
        id = request.args.get('id')
        cover = request.files.get('cover')
        coverFilename = str(uuid.uuid4()) + '.' + cover.filename.replace('"', '').split('.')[-1]
        save_path = os.path.join(app.root_path, 'static', 'houseImg', coverFilename)
        cover.save(save_path)
        edithouseInfo({
            'title': request.form.get('title'),
            'city': request.form.get('city'),
            'region': request.form.get('region'),
            'address': request.form.get('address'),
            'rooms_desc': request.form.get('rooms_desc'),
            'area_range': request.form.get('area_range'),
            'price': request.form.get('price'),
            'houseDecoration': request.form.get('houseDecoration'),
            'company': request.form.get('company'),
            'houseType': request.form.get('houseType'),
            'tags': request.form.get('tags'),
            'cover': os.path.join('http://localhost:5000', 'static', 'houseImg', coverFilename)
        },id)
        return redirect('/page/tableData')

@pb.route('/addhouse',methods=['GET','POST'])
def addhouse():
    username = session['username']
    if request.method == 'GET':
        return render_template(
            "addhouse.html",
            username=username
        )
    else:
        cover = request.files.get('cover')
        coverFilename = str(uuid.uuid4()) + '.' + cover.filename.replace('"', '').split('.')[-1]
        save_path = os.path.join(app.root_path, 'static', 'houseImg',coverFilename)
        cover.save(save_path)
        addhouseInfo({
            'title': request.form.get('title'),
            'city': request.form.get('city'),
            'region': request.form.get('region'),
            'address': request.form.get('address'),
            'rooms_desc': request.form.get('rooms_desc'),
            'area_range': request.form.get('area_range'),
            'price': request.form.get('price'),
            'houseDecoration': request.form.get('houseDecoration'),
            'company': request.form.get('company'),
            'houseType': request.form.get('houseType'),
            'tags': request.form.get('tags'),
            'cover': os.path.join('http://localhost:5000', 'static', 'houseImg',coverFilename)
        })

    return redirect('/page/tableData')

@pb.route('/priceChar',methods=['GET','POST'])
def priceChar():
    username = session['username']
    cityList = getCityList()
    if request.args.get('city'):defaultCity=request.args.get('city')
    else :defaultCity = cityList[0]
    hList = getAllhouseInfoDataMap(defaultCity)
    xData,y1Data = getPriceCityData(hList)
    x1Data,y2Data = getOpen_dateCityData(hList)
    scallerData = getTotalPriceData(hList)
    return render_template('priceChar.html',
                               username=username,
                               cityList=cityList,
                               xData=xData,
                               y1Data=y1Data,
                           x1Data=x1Data,
                           y2Data=y2Data,
                               defaultCity=defaultCity,
                           scallerData=scallerData
                          )

@pb.route('/detailChar',methods=['GET','POST'])
def detailChar():
    username = session['username']
    houseList = getAllhouseInfoDataMap()
    dataDic = getDetailCharRomms_descData(houseList)
    defaultType = 'small'
    if request.args.get('type'):defaultType = request.args.get('type')
    xData,yData = getDetailCharArea_rangeData(houseList,defaultType)
    return render_template('detailChar.html',
                           username=username,
                           dataDic=dataDic,
                           xData=xData,
                           yData=yData
                          )

@pb.route('/typeChar',methods=['GET','POST'])
def typeChar():
    username = session['username']
    cityList = getCityList()
    if request.args.get('city'):
        defaultCity = request.args.get('city')
    else:
        defaultCity = cityList[0]
    hList = getAllhouseInfoDataMap(defaultCity)
    houseDecorationData = getTypeCharhouseDecorationData(hList)
    houseTypeData = getTypeCharhouseTypeData(hList)
    return render_template('typeChar.html',
                           username=username,
                           cityList=cityList,
                           defaultCity=defaultCity,
                           houseDecorationData=houseDecorationData,
                           houseTypeData=houseTypeData
                          )

@pb.route('/lpCloud',methods=['GET','POST'])
def lpCloud():
    username = session['username']
    return render_template('lpCloud.html',
                           username=username
                          )

@pb.route('/tagCloud',methods=['GET','POST'])
def tagCloud():
    username = session['username']
    return render_template('tagCloud.html',
                           username=username
                          )

@pb.route('/anthorChar',methods=['GET','POST'])
def anthorChar():
    username = session['username']
    houseList = getAllhouseInfoDataMap()
    saleStatusData = getAnthorCharSale_statusData(houseList)
    xData,yData =   getAnthorCharOn_timeData(houseList)
    x1Data,y1Data = getTagData(houseList)
    return render_template('anthorChar.html',
                           username=username,
                           saleStatusData=saleStatusData,
                           xData=xData,
                           yData=yData,
                           x1Data=x1Data,
                           y1Data=y1Data
                          )

@pb.route('/model',methods=['GET','POST'])
def model():
    username = session['username']
    cityList = getCityList()
    if request.method == 'GET':
        return render_template('model.html',
                               username=username,
                               cityList=cityList,
                               priceResult = 0
                              )
    else:
        model = index.model_train(index.getData())
        if request.form.get("sale_status") == '在售':
            sale_status = 1
        elif request.form.get("sale_status") == '已售':
            sale_status = 2
        elif request.form.get("sale_status") == '出租中':
            sale_status = 3
        elif request.form.get("sale_status") == '已出租':
            sale_status = 4
        elif request.form.get("sale_status") == '预售':
            sale_status = 5
        elif request.form.get("sale_status") == '其他':
            sale_status = 6
        price = index.pred(model, request.form.get("city") , int(request.form.get("rooms_desc")) , int(request.form.get("area_range")) , request.form.get("houseType") ,  sale_status)

        addHistory(username,request.form.get("city"),round(price,1))
        return render_template('model.html',
                               username=username,
                               cityList=cityList,
                               priceResult= round(price,1)
                               )
